import {
	Plugin,
	Notice,
	TFile,
	App,
	Modal,
	ButtonComponent,
	TextComponent,
} from "obsidian";

import path, { join } from "path";
import { readFileSync } from "fs";

function getImageAsBase64(plugin: Plugin, imagePath: string): string {
	const adapter: any = plugin.app.vault.adapter;
	if (plugin.manifest && plugin.manifest.dir && adapter && adapter.basePath) {
		const imageFilePath = join(
			adapter.basePath + path.sep,
			plugin.manifest.dir,
			imagePath
		);
		const buffer = readFileSync(imageFilePath);
		const mimeType = imagePath.endsWith(".png")
			? "image/png"
			: imagePath.endsWith(".jpg") || imagePath.endsWith(".jpeg")
				? "image/jpeg"
				: imagePath.endsWith(".svg")
					? "image/svg+xml"
					: "image/*";

		return `data:${mimeType};base64,${buffer.toString("base64")}`;
	}
	return "";
}

interface NavigationItem {
	url: string;
	label: string;
	star: boolean;
}

class NavigationModal extends Modal {
	plugin: NavigationCardsPlugin;
	navigationData: NavigationItem[] = [];
	filteredData: NavigationItem[] = [];
	searchTerm: string = "";
	private cardsContainer: HTMLElement;

	constructor(app: App, plugin: NavigationCardsPlugin) {
		super(app);
		this.plugin = plugin;
	}

	async onOpen() {
		this.modalEl.style.width = "1200px";
		this.modalEl.style.height = "100%";
		this.modalEl.style.overflow = "hidden";
		this.modalEl.style.paddingRight = "0";

		this.contentEl.empty();
		this.contentEl.addClass("navigation-modal");

		this.renderHeader();
		this.renderToolbar();
		this.renderCardContainer();
		await this.refreshDataAndRender();
	}

	/**
	 * 统一的数据刷新与渲染入口
	 */
	async refreshDataAndRender() {
		await this.loadNavigationData();
		this.filterData();
		this.renderCards();
	}

	async loadNavigationData() {
		this.navigationData = await this.plugin.readNavigationData();
	}

	sortData() {
		this.filteredData.sort((a, b) => {
			if (a.star && !b.star) return -1;
			if (!a.star && b.star) return 1;
			return a.label.localeCompare(b.label);
		});
	}

	renderHeader() {
		const title = this.titleEl.createEl("div", { text: "导航卡片" });
		title.className = "navigation-modal-title";
	}

	renderToolbar() {
		const toolbar = this.contentEl.createDiv({
			cls: "navigation-modal-toolbar",
		});

		//左边
		const buttonContainer = toolbar.createDiv({
			cls: "navigation-modal-toolbar-left",
		});

		new ButtonComponent(buttonContainer)
			.setButtonText("＋添加")
			.setCta()
			.onClick(() => this.addNavigationItem(null))
			.buttonEl.addClass("navigation-modal-toolbar-add-button");

		//右边
		const searchContainer = toolbar.createDiv({
			cls: "navigation-modal-toolbar-right",
		});

		new TextComponent(searchContainer)
			.setPlaceholder("请输入标签或链接进行搜索...")
			.onChange((value) => {
				this.searchTerm = value.toLowerCase();
				this.filterData();
			})
			.inputEl.addClass("navigation-modal-toolbar-search-input");

		searchContainer.createEl("span", { cls: "navigation-modal-toolbar-search-icon" });
	}

	renderCardContainer() {
		this.cardsContainer = this.contentEl.createDiv({
			cls: "navigation-modal-cards-container",
		});
	}

	filterData() {
		this.filteredData = this.searchTerm
			? this.navigationData.filter(
				(item) =>
					item.label.toLowerCase().includes(this.searchTerm) ||
					item.url.toLowerCase().includes(this.searchTerm)
			)
			: [...this.navigationData];
		this.sortData();
		this.renderCards();
	}

	renderCards() {
		this.cardsContainer.empty();

		if (this.filteredData.length === 0) {
			this.cardsContainer.className = "navigation-modal-cards-container-empty";
			const emptyImg = getImageAsBase64(this.plugin, "assets/empty.svg");

			const emptyContainer = this.cardsContainer.createDiv({
				cls: "empty-navigation-modal-empty-container",
			});

			if (emptyImg) {
				emptyContainer.createEl("img", {
					cls: "navigation-modal-empty-img",
					attr: {
						src: emptyImg,
					},
				});
			}

			emptyContainer.createDiv({
				cls: "navigation-modal-empty-label",
				text: "暂无数据",
			});

			return;
		} else {
			this.cardsContainer.className = "navigation-modal-cards-container";
		}

		this.filteredData.forEach((item) => {
			const card = this.cardsContainer.createDiv({
				cls: "navigation-modal-navigation-card",
			});
			if (item.star) card.addClass("starred");

			card.createDiv({
				text: item.label,
				cls: "navigation-modal-navigation-card-label",
				attr: { title: item.label },
			});
			card.createDiv({
				text: item.url,
				cls: "navigation-modal-navigation-card-url",
				attr: { title: item.url },
			});

			const actions = card.createDiv({ cls: "navigation-modal-navigation-card-actions" });

			// 星标按钮
			const starButton = actions.createEl("button", {
				cls: `navigation-modal-star-button ${item.star ? "active" : ""}`,
				attr: { title: item.star ? "取消星标" : "标为星标" },
				text: "★",
			});
			starButton.onclick = async (e) => {
				e.stopPropagation();
				item.star = !item.star;
				await this.plugin.writeNavigationData(this.navigationData);
				await this.refreshDataAndRender();
				new Notice(item.star ? "已标为星标" : "已取消星标");
			};

			// 编辑按钮
			const editButton = actions.createEl("button", {
				cls: "navigation-modal-edit-button",
				attr: { title: "编辑" },
				text: "✎",
			});
			editButton.onclick = (e) => {
				e.stopPropagation();
				this.addNavigationItem(item);
			};

			// 删除按钮
			const deleteButton = actions.createEl("button", {
				cls: "navigation-modal-delete-button",
				attr: { title: "删除" },
				text: "✕",
			});
			deleteButton.onclick = async (e) => {
				e.stopPropagation();
				if (confirm(`确定要删除"${item.label}"吗?`)) {
					this.navigationData = this.navigationData.filter(
						(i) => !(i.label === item.label && i.url === item.url)
					);
					await this.plugin.writeNavigationData(this.navigationData);
					await this.refreshDataAndRender();
					new Notice("删除成功");
				}
			};


			card.onclick = () => {
				window.open(item.url, '_blank');
			};
		});
	}

	async addNavigationItem(item: NavigationItem | null) {
		// 移除可能存在的旧编辑框
		this.contentEl
			.querySelectorAll(".edit-overlay")
			.forEach((el) => el.remove());

		let original = {};
		if (item) {
			original = { ...item };
		}

		const overlay = this.contentEl.createDiv({ cls: "edit-overlay" });
		overlay.onclick = (e) => e.stopPropagation();

		const modal = overlay.createDiv({ cls: "navigation-modal-edit-modal" });
		modal.createEl("h3", { text: "添加新导航" });

		const form = modal.createEl("form");

		// 标签输入
		const labelGroup = form.createDiv({ cls: "navigation-modal-edit-modal-form-group" });
		labelGroup.createEl("label", {
			cls: "navigation-modal-edit-modal-label",
			text: "标签:",
			attr: { for: "new-label" },
		});
		const labelInput = labelGroup.createEl("input", {
			type: "text",
			cls: "navigation-modal-edit-modal-input",
			value: item && item.label ? item.label : "",
			attr: {
				required: "true",
				tabIndex: "1",
				placeholder: "请输入标签名称!",
			},
		});
		labelInput.id = "new-label";
		labelInput.focus();

		// URL输入
		const urlGroup = form.createDiv({ cls: "navigation-modal-edit-modal-form-group" });
		urlGroup.createEl("label", {
			cls: "navigation-modal-edit-modal-label",
			text: "链接:",
			attr: { for: "new-url" },
		});
		const urlInput = urlGroup.createEl("input", {
			type: "url",
			cls: "navigation-modal-edit-modal-input",
			value: item && item.url ? item.url : "",
			attr: {
				required: "true",
				tabIndex: "2",
				placeholder: "请输入链接地址!",
			},
		});
		urlInput.id = "new-url";

		// 星标选项
		const starGroup = form.createDiv({ cls: "navigation-modal-edit-modal-star-form-group" });
		const starLabel = starGroup.createEl("label", {
			cls: "navigation-modal-edit-modal-start-label",
			text: "星标:",
			attr: { for: "new-star" },
		});
		const starInput = starGroup.createEl("input", {
			type: "checkbox",
			attr: { tabIndex: "3" },
		});
		starInput.id = "new-star";
		if (item) {
			starInput.checked = item.star;
		}

		// 按钮组
		const buttons = form.createDiv({ cls: "navigation-modal-edit-modal-button-group" });

		const saveBtn = buttons.createEl("button", {
			cls: "mod-cta",
			text: "保存",
			type: "submit",
		});

		const cancelBtn = buttons.createEl("button", {
			text: "取消",
			type: "button",
		});

		if (item) {
			cancelBtn.onclick = () => {
				Object.assign(item, original);
				overlay.remove();
			};
		} else {
			cancelBtn.onclick = () => overlay.remove();
		}

		form.onsubmit = async (e) => {
			e.preventDefault();
			try {
				new URL(urlInput.value);
			} catch {
				new Notice("无效的链接（必须包含 http:// 或 https://）");
				urlInput.focus();
				return;
			}

			if (item) {
				item.label = labelInput.value;
				item.url = urlInput.value;
				item.star = starInput.checked;

				await this.plugin.writeNavigationData(this.navigationData);
				overlay.remove();
				await this.refreshDataAndRender();
				new Notice("更新成功");
			} else {
				this.navigationData.push({
					label: labelInput.value,
					url: urlInput.value,
					star: starInput.checked,
				});

				await this.plugin.writeNavigationData(this.navigationData);
				overlay.remove();
				await this.refreshDataAndRender();
				new Notice("添加成功");
			}
		};

		// 确保输入框可交互
		[labelInput, urlInput, starInput, cancelBtn, saveBtn].forEach((el) => {
			el.onmousedown = (e) => e.stopPropagation();
			el.onfocus = (e) => e.stopPropagation();
		});
	}

	onClose() {
		this.contentEl.empty();
	}
}

export default class NavigationCardsPlugin extends Plugin {
	async onload() {
		console.log("导航卡片插件已加载");

		this.addRibbonIcon("link", "导航卡片", () => {
			new NavigationModal(this.app, this).open();
		});

		this.addCommand({
			id: "open-navigation-cards",
			name: "打开导航卡片",
			callback: () => new NavigationModal(this.app, this).open(),
		});
	}

	onunload() {
		console.log("导航卡片插件已卸载");
	}

	async readNavigationData(): Promise<NavigationItem[]> {
		try {
			const file = this.app.vault.getAbstractFileByPath(
				"navigation-cards.json"
			);
			if (file instanceof TFile) {
				const data = JSON.parse(await this.app.vault.read(file));
				return Array.isArray(data)
					? data.filter(this.validateItem)
					: [];
			}
			await this.writeNavigationData([]);
			return [];
		} catch (e) {
			new Notice("读取数据失败: " + (e as Error).message);
			return [];
		}
	}

	async writeNavigationData(data: NavigationItem[]) {
		try {
			const content = JSON.stringify(
				data.filter(this.validateItem),
				null,
				2
			);
			const file = this.app.vault.getAbstractFileByPath(
				"navigation-cards.json"
			);

			if (file instanceof TFile) {
				await this.app.vault.modify(file, content);
			} else {
				await this.app.vault.create("navigation-cards.json", content);
			}
		} catch (e) {
			new Notice("保存数据失败: " + (e as Error).message);
		}
	}

	private validateItem(item: any): item is NavigationItem {
		return (
			typeof item === "object" &&
			typeof item.label === "string" &&
			typeof item.url === "string" &&
			typeof item.star === "boolean"
		);
	}
}
